package com.lbb.xcx.controller;

import com.alibaba.fastjson.JSON;
import com.lbb.springboot.entity.ServiceResult;
import com.lbb.springboot.util.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

@Api(description = "文件上传接口")
@Controller
public class FileCloudUploadController {


    @Value("${filePath}")
    private String filePath;

//    @Autowired
//    private IScaleService scaleService;

    /**
     * 实现文件上传
     */
    @ApiOperation(value = "文件上传")
    @RequestMapping("fileUpload")
    @ResponseBody
    public ServiceResult fileUpload(@RequestParam("fileName") MultipartFile file) {
//        System.o
        if (file.isEmpty()) {
            return ServiceResult.fail();
        }
//        String fileName = DateUtil.getNowDate() + UUID.randomUUID().toString().substring(0, 8) +
//                file.getOriginalFilename();

        String[] split =  file.getOriginalFilename().split("\\.");
        System.out.println(JSON.toJSON(split));
        String fileLastName = "."+split[split.length-1];
        String fileName = "java" + DateUtil.getNowDate() + UUID.randomUUID().toString().substring(0, 8) + fileLastName;


        int size = (int) file.getSize();
        System.out.println("fileName:" + fileName + "-->" + size);

//        String path = "F:/test";
        File dest = new File(filePath + "/" + DateUtil.getNowDateForYyyyMm() + "/" + fileName);
        if (!dest.getParentFile().exists()) { //判断文件父目录是否存在
            dest.getParentFile().mkdir();
        }
        try {
            file.transferTo(dest); //保存文件
            return new ServiceResult(DateUtil.getNowDateForYyyyMm() + "/" + fileName);
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return ServiceResult.fail();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return ServiceResult.fail();
        }
    }



    /**
     * 实现文件上传
     */
    @ApiOperation(value = "文件上传比例尺")
    @RequestMapping("fileUploadScale")
    @ResponseBody
    public ServiceResult fileUploadScale(@RequestHeader String token, @RequestParam("fileName") MultipartFile file) {
        if (file.isEmpty()) {
            return ServiceResult.fail();
        }

        String[] split =  file.getOriginalFilename().split("\\.");
        System.out.println(JSON.toJSON(split));
        String fileLastName = "."+split[split.length-1];
        String fileName = "java" + DateUtil.getNowDate() + UUID.randomUUID().toString().substring(0, 8) + fileLastName;

        int size = (int) file.getSize();
        System.out.println("fileName:" + fileName + "-->" + size);

//        String path = "F:/test";
        File dest = new File(filePath + "/" + DateUtil.getNowDateForYyyyMm() + "/" + fileName);
        if (!dest.getParentFile().exists()) { //判断文件父目录是否存在
            dest.getParentFile().mkdir();
        }
        try {
            file.transferTo(dest); //保存文件


//            Scale scale = new Scale();
//            scale.setToken(token);
//            scale.setImg(DateUtil.getNowDateForYyyyMm() + "/" + fileName);
//            scale.setImgName(DateUtil.getNowDateForYyyyMm() + "/" + fileName);
//            boolean save = scaleService.saveOrUpdate(scale);
            return new ServiceResult(DateUtil.getNowDateForYyyyMm() + "/" + fileName);
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return ServiceResult.fail();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return ServiceResult.fail();
        }
    }




    @ApiOperation(value = "文件下载")
    @RequestMapping("download")
    public String downLoad(HttpServletResponse response, String filename) {
//        String filename = "2.bmp";
        System.out.println(filename);
        File file = null;
//        if (filename.contains("/")) {
//            String month = filename.split("/")[0];
//            file = new File(filePath + "/" + month + "/" + filename);
//        } else {
        file = new File(filePath + "/" + filename);
//        }
        System.out.println(file.getAbsoluteFile());
        if (file.exists()) { //判断文件父目录是否存在
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment;fileName=" + filename);

            byte[] buffer = new byte[1024];
            FileInputStream fis = null; //文件输入流
            BufferedInputStream bis = null;

            OutputStream os = null; //输出流
            try {
                os = response.getOutputStream();
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer);
                    i = bis.read(buffer);
                }

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return null;
    }
}
